package com.ihemou.system.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.ihemou.common.core.constant.Constants;
import com.ihemou.common.core.constant.UserConstants;
import com.ihemou.common.core.utils.StringUtils;
import com.ihemou.common.security.utils.SecurityUtils;
import com.ihemou.system.domain.SysSocialUser;
import com.ihemou.system.domain.SysUser;
import com.ihemou.system.domain.SysUserSocialUser;
import com.ihemou.system.dto.WxUserInfoDTO;
import com.ihemou.system.mapper.SysSocialUserMapper;
import com.ihemou.system.mapper.SysUserMapper;
import com.ihemou.system.mapper.SysUserSocialUserMapper;
import com.ihemou.system.service.ISysSocialUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * All rights Reserved, Designed By saperliu
 * Copyright:    Copyright(C) 2021-2021
 * 社交账号Service业务层处理
 *
 * @author saperliu
 * @date 2021年09月02日
 */
@Service
public class SysSocialUserServiceImpl implements ISysSocialUserService {
    @Autowired
    private SysSocialUserMapper sysSocialUserMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserSocialUserMapper sysUserSocialUserMapper;



    /**
     * 根据条件分页查询社交账号数据
     *
     * @param sysSocialUser 过滤条件
     * @return 社交账号数据集合信息
     */
    @Transactional(readOnly = true)
    @Override
    public List<SysSocialUser> findSysSocialUserByCondition(SysSocialUser sysSocialUser) {

        return sysSocialUserMapper.findSysSocialUserByCondition(sysSocialUser);
    }


    /**
     * 查询社交账号
     *
     * @param id 社交账号ID
     * @return 社交账号
     */
    @Transactional(readOnly = true)
    @Override
    public SysSocialUser selectSysSocialUserById(String id) {
        return sysSocialUserMapper.selectById(id);
    }


    /**
     * 新增社交账号
     *
     * @param sysSocialUser 社交账号
     * @return 结果
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int insertSysSocialUser(SysSocialUser sysSocialUser) {
        return sysSocialUserMapper.insert(sysSocialUser);
    }

    /**
     * 修改社交账号
     *
     * @param sysSocialUser 社交账号
     * @return 结果
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int updateSysSocialUser(SysSocialUser sysSocialUser) {
        return sysSocialUserMapper.updateById(sysSocialUser);
    }

    /**
     * 批量删除社交账号
     *
     * @param ids 需要删除的社交账号ID
     * @return 结果
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int deleteSysSocialUserByIds(String[] ids) {

        return sysSocialUserMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除社交账号信息
     *
     * @param id 社交账号ID
     * @return 结果
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int deleteSysSocialUserById(String id) {
        return sysSocialUserMapper.deleteById(id);
    }


    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SysUser saveWxSocialUser(WxUserInfoDTO wxUserInfoDTO) {
        //先判断是否已经存在此用户
        SysUserSocialUser userSocialUser = sysUserSocialUserMapper.findSysUserSocialUserByOpenId(wxUserInfoDTO.getOpenId());
        if(userSocialUser!=null){
            SysUser sysUser = sysUserMapper.selectUserById(userSocialUser.getUserId());
            if(StringUtils.isNotEmpty(wxUserInfoDTO.getNickName())){
                // 更新一下头像和昵称
                sysUser.setNickName(wxUserInfoDTO.getNickName());
                sysUser.setAvatar(wxUserInfoDTO.getAvatarUrl());
                sysUser.setSex(wxUserInfoDTO.getGender().toString());
                sysUserMapper.updateUser(sysUser);
            }else{
                if(StringUtils.isNotEmpty(wxUserInfoDTO.getPurePhoneNumber())){
                    sysUser.setPhoneNumber(wxUserInfoDTO.getPurePhoneNumber());
                    sysUserMapper.updateUser(sysUser);
                }
            }
            return sysUser;
        }else {
            // 创建系统用户
            Date date = new Date();
            String wxName = "wx_" + System.currentTimeMillis();
            SysUser sysUser = new SysUser();
            if(StringUtils.isNotEmpty(wxUserInfoDTO.getNickName())){
                sysUser.setNickName(wxUserInfoDTO.getNickName());
                sysUser.setSex(wxUserInfoDTO.getGender().toString());
                sysUser.setAvatar(wxUserInfoDTO.getAvatarUrl());
            }else {
                sysUser.setNickName(RandomUtil.randomString(10).toUpperCase());
                sysUser.setSex("1");
                // 未判断手机号已经存在
                sysUser.setPhoneNumber(wxUserInfoDTO.getPurePhoneNumber());
            }
            sysUser.setLoginDate(date);
            sysUser.setUserName(wxName);
            sysUser.setUpdateBy("system");
            sysUser.setUpdateTime(date);
            sysUser.setCreateBy("system");
            sysUser.setCreateTime(date);
            sysUser.setDelFlag(UserConstants.NORMAL);
            if(UserConstants.USER_REQUIRE_APPROVE_Y.equals(wxUserInfoDTO.getExamineUser())){
                sysUser.setStatus(UserConstants.USER_APPROVE);
            }else {
                sysUser.setStatus(UserConstants.NORMAL);
            }
            sysUser.setPassword(SecurityUtils.encryptPassword(RandomUtil.randomString(10)));
            sysUser.setDeptId(wxUserInfoDTO.getDeptId());
            sysUserMapper.insert(sysUser);
            // 创建社交账号
            SysSocialUser socialUser = new SysSocialUser();
            socialUser.setOpenId(wxUserInfoDTO.getOpenId());
            socialUser.setUnionId(wxUserInfoDTO.getUnionId());
            socialUser.setSource(Constants.USER_SOURCE_WX_MINI_PROGRAM);
            socialUser.setAppCode(wxUserInfoDTO.getAppCode());
            socialUser.setUpdateBy("system");
            socialUser.setUpdateTime(date);
            socialUser.setCreateBy("system");
            socialUser.setCreateTime(date);
            sysSocialUserMapper.insert(socialUser);

            SysUserSocialUser sysUserSocialUser = new SysUserSocialUser();
            sysUserSocialUser.setSocialUserId(socialUser.getId());
            sysUserSocialUser.setUserId(sysUser.getId());
            sysUserSocialUser.setUpdateBy("system");
            sysUserSocialUser.setUpdateTime(date);
            sysUserSocialUser.setCreateBy("system");
            sysUserSocialUser.setCreateTime(date);
            sysUserSocialUserMapper.insert(sysUserSocialUser);
            return sysUser;
        }

    }

    @Transactional(readOnly = true)
    @Override
    public SysUser findWxSocialUser(WxUserInfoDTO wxUserInfoDTO) {
        List<SysUser> list = sysSocialUserMapper.findSysUserBySocial(wxUserInfoDTO);
        if(list!=null && list.size()==1){
            return  list.get(0);
        }else{
            return null;
        }
    }
}
